package cn.cupster.floatwindowdemo

import android.app.AlertDialog
import android.app.Dialog
import android.content.ComponentName
import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.content.Intent
import android.content.ServiceConnection
import android.net.Uri
import android.os.Build
import android.os.IBinder
import android.provider.Settings
import android.util.Log
import android.widget.Toast
import java.lang.Exception


class MainActivity : AppCompatActivity() {

    companion object{
        private const val TAG = "MainActivity"
    }
    private lateinit var mTvShow : View
    private lateinit var runTask : Runnable
    private var count = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        mTvShow = findViewById<View>(R.id.btnShowWindow)
        mTvShow.setOnClickListener {
            showFloatWindow()
        }
        findViewById<View>(R.id.btnCloseWindow).setOnClickListener{
            show("已关闭")
            unbindService(mServiceConnection)
        }

        runTask = Runnable {
            mTvShow.removeCallbacks(runTask)
            count++
            mService?.updateData("data:$count")
            mTvShow.postDelayed(runTask , 1000)
        }
    }

    private fun showFloatWindow() {
        if (!commonROMPermissionCheck(this)) {
            commonROMPermissionApply(this)
            return
        }
        //
//        startService(Intent(this@MainActivity, FloatWindowServiceDrag::class.java))
        //bind方式
        bindService(Intent(this@MainActivity, FloatWindowServiceDrag::class.java)
            , mServiceConnection
            , Context.BIND_AUTO_CREATE)
    }


    var mService: FloatWindowServiceDragBind? =null
    private val mServiceConnection: ServiceConnection = object : ServiceConnection {
        override fun onServiceConnected(name: ComponentName, service: IBinder) {
            // 获取服务的操作对象
            val binder: FloatWindowServiceDragBind.WindowBinder =
                service as FloatWindowServiceDragBind.WindowBinder
            mService = binder.obtainService()
            //模拟数据变化
            mTvShow.postDelayed(runTask ,1000)
        }

        override fun onServiceDisconnected(name: ComponentName) {}
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 0) {
            if (!commonROMPermissionCheck(this)) {
                show("授权失败")
            } else {
                show("授权成功")
               showFloatWindow()
            }
        }
    }

    private fun commonROMPermissionCheck(context: Context?): Boolean {
        var result = true
        if (Build.VERSION.SDK_INT >= 25) {
            try {
                val clazz: Class<*> = Settings::class.java
                val canDrawOverlays = clazz.getDeclaredMethod(
                    "canDrawOverlays",
                    Context::class.java
                )
                result = canDrawOverlays.invoke(null, context) as Boolean
            } catch (e: Exception) {
                Log.e(
                    "MainActivity",
                    Log.getStackTraceString(e)
                )
            }
        }
        return result
    }

    private fun show(s: String) {
        Toast.makeText(this,s ,Toast.LENGTH_SHORT).show()
    }

    fun commonROMPermissionApply(context: Context) {
        if (Build.VERSION.SDK_INT >= 25) {
            showConfirmDialog(context, object : OnConfirmResult {
                override fun confirmResult(confirm: Boolean) {
                    if (confirm) {
                        try {
                            val clazz: Class<*> = Settings::class.java
                            val field = clazz.getDeclaredField("ACTION_MANAGE_OVERLAY_PERMISSION")
                            val intent = Intent(field[null].toString())
                            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                            intent.data = Uri.parse("package:" + context.packageName)
                            context.startActivity(intent)
                        } catch (e: Exception) {
                            Log.e(
                                TAG,
                                Log.getStackTraceString(e)
                            )
                        }
                    } else {
                        Log.d(
                            TAG,
                            "user manually refuse OVERLAY_PERMISSION"
                        )
                    }
                }
            })
        }
    }

    private fun showConfirmDialog(context: Context, result: OnConfirmResult) {
        showConfirmDialog(context, "您的手机没有授予悬浮窗权限，请开启后再试", result)
    }

    private fun showConfirmDialog(context: Context, message: String, result: OnConfirmResult) {
        val dialog: Dialog = AlertDialog.Builder(context).setCancelable(true).setTitle("")
            .setMessage(message)
            .setPositiveButton(
                "现在去开启"
            ) { dialog, which ->
                result.confirmResult(true)
                dialog.dismiss()
            }.setNegativeButton(
                "暂不开启"
            ) { dialog, which ->
                result.confirmResult(false)
                dialog.dismiss()
            }.create()
        dialog.show()
    }

    private interface OnConfirmResult {
        fun confirmResult(confirm: Boolean)
    }

}